﻿using System;
using System.Linq;
using System.Web.ModelBinding;
using System.Web.UI.WebControls;
using Altairis.FluffyCloud.Data;

namespace Altairis.FluffyCloud.WebCore.Pages.Groups {

    public partial class Detail : System.Web.UI.Page {

        public object[] AddUserList_GetData() {
            using (var dc = new FluffyDbContext()) {
                var q = from u in dc.Users
                        where u.IsApproved
                        orderby u.UserName
                        select new {
                            Text = u.UserName.ToUpper() + (string.IsNullOrEmpty(u.Comment) ? "" : " (" + u.Comment.Trim() + ")"),
                            Value = u.UserName
                        };
                return q.ToArray();
            }
        }

        public void FormView_DeleteItem(string roleName) {
            using (var dc = new FluffyDbContext()) {
                var r = dc.Roles.SingleOrDefault(x => x.RoleName.Equals(roleName, StringComparison.CurrentCultureIgnoreCase));
                if (r != null) {
                    dc.Roles.Remove(r);
                    dc.SaveChanges();
                }
            }
            this.Response.RedirectToRoute("GroupList");
        }

        public Role FormView_GetItem([RouteData]string roleName) {
            using (var dc = new FluffyDbContext()) {
                var r = dc.Roles.SingleOrDefault(x => x.RoleName.Equals(roleName, StringComparison.CurrentCultureIgnoreCase));
                if (r == null) {
                    // Role not found - create
                    this.FormView.ChangeMode(FormViewMode.Insert);
                }
                else if (r.RoleName.StartsWith(this.User.Identity.Name, StringComparison.CurrentCultureIgnoreCase)) {
                    // My role - edit
                    this.FormView.ChangeMode(FormViewMode.Edit);
                }
                else {
                    // System or others - view only
                    this.FormView.ChangeMode(FormViewMode.ReadOnly);
                }
                return r;
            }
        }

        public void FormView_InsertItem() {
            if (!this.IsValid) return;

            var item = new Role();
            TryUpdateModel(item);
            item.RoleName = this.User.Identity.Name + "$" + item.RoleName;
            if (!ModelState.IsValid) return;

            using (var dc = new FluffyDbContext()) {
                if (dc.Roles.Any(x => x.RoleName.Equals(item.RoleName, StringComparison.CurrentCultureIgnoreCase))) {
                    this.ModelState.AddModelError("DuplicateEntry", "Skupina s tímto jménem už existuje");
                    return;
                }
                dc.Roles.Add(item);
                try {
                    dc.SaveChanges();
                    this.Response.RedirectToRoute("GroupDetail", new { rolename = item.RoleName });
                }
                catch (Exception ex) {
                    this.ModelState.AddModelError("SaveException", ex);
                }
            }
        }

        public void FormView_UpdateItem(string roleName) {
            if (!this.IsValid) return;

            using (var dc = new FluffyDbContext()) {
                var item = dc.Roles.SingleOrDefault(x => x.RoleName.Equals(roleName));
                if (item == null) {
                    ModelState.AddModelError("NotFound", "Role nebyla nalezena");
                    return;
                }
                TryUpdateModel(item);
                if (!ModelState.IsValid) return;
                try {
                    dc.SaveChanges();
                    this.Response.RedirectToRoute("GroupList");
                }
                catch (Exception ex) {
                    this.ModelState.AddModelError("SaveException", ex);
                }
            }
        }

        public void UserList_DeleteItem([RouteData]string roleName, string userName) {
            using (var dc = new FluffyDbContext()) {
                var r = dc.Roles.SingleOrDefault(x => x.RoleName.Equals(roleName, StringComparison.CurrentCultureIgnoreCase));
                var u = r.Users.SingleOrDefault(x => x.UserName.Equals(userName, StringComparison.CurrentCultureIgnoreCase));
                if (u == null) return; // already out
                r.Users.Remove(u);
                dc.SaveChanges();
            }
            this.Response.Redirect(this.Request.Url.ToString());
        }

        public IQueryable<User> UserList_GetData([RouteData]string roleName) {
            using (var dc = new FluffyDbContext()) {
                var r = dc.Roles.SingleOrDefault(x => x.RoleName.Equals(roleName, StringComparison.CurrentCultureIgnoreCase));
                return r.Users.Where(x => x.IsApproved).OrderBy(x => x.UserName).AsQueryable();
            }
        }

        public void UserList_InsertItem([RouteData]string roleName) {
            var item = new User();
            TryUpdateModel(item);
            this.ModelState.Clear();

            using (var dc = new FluffyDbContext()) {
                var r = dc.Roles.SingleOrDefault(x => x.RoleName.Equals(roleName, StringComparison.CurrentCultureIgnoreCase));
                if (r.Users.Any(x => x.UserName.Equals(item.UserName, StringComparison.CurrentCultureIgnoreCase))) return; // already member
                r.Users.Add(dc.Users.Single(x => x.UserName.Equals(item.UserName, StringComparison.CurrentCultureIgnoreCase)));
                dc.SaveChanges();
            }
            this.Response.Redirect(this.Request.Url.ToString());
        }
    }
}